package com.spark.gaea.utils;

import com.google.common.collect.Lists;

import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.Collections;
import java.util.List;

public final class ReflectUtil {
	public static List<Field> getAllFieldsForClass(final Class<?> cmdClass, final Class<?> baseClass) {
		final List<Field> fields = Lists.newArrayList();
		Collections.addAll(fields, cmdClass.getDeclaredFields());
		for (Class<?> superClass = cmdClass.getSuperclass();
			 baseClass.isAssignableFrom(superClass) && baseClass != superClass; superClass = superClass
				.getSuperclass()) {
			final Field[] superClassFields = superClass.getDeclaredFields();
			if (superClassFields != null) {
				Collections.addAll(fields, superClassFields);
			}
		}
		return fields;
	}

	public static boolean isBaseType(final Field field) {
		final Class typeClass = field.getType();
		return typeClass.isPrimitive();
	}

	public static void setValueToDefault(final Field field, final Object obj) {
		if (!isBaseType(field)) {
			try {
				field.set(obj, null);
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
		} else {
			final Type type = field.getType();
			try {
				if (type == Long.TYPE) {
					field.setLong(obj, 0L);
				} else if (type == Integer.TYPE) {
					field.setInt(obj, 0);
				} else if (type == Boolean.TYPE) {
					field.setBoolean(obj, false);
				} else if (type == Float.TYPE) {
					field.setFloat(obj, 0.0f);
				} else if (type == Double.TYPE) {
					field.setDouble(obj, 0.0);
				} else if (type == Short.TYPE) {
					field.setShort(obj, (short) 0);
				} else if (type == Byte.TYPE) {
					field.setByte(obj, (byte) 0);
				} else if (type == Character.TYPE) {
					field.setChar(obj, '\0');
				}
			} catch (IllegalAccessException e2) {
				e2.printStackTrace();
			}
		}
	}
}
